<?php

class TemplateService extends FServiceBase
{    
    /**
    * Get a Template model given its ID
    * 
    * @param int id Template ID
    * @return FServiceModel
    */
    public function get($params){
        $templateId = $this->getParam($params, 'id',0);
        $revisionId = $this->getParam($params, 'revision_id',0);
        
        if ($revisionId)
        {
            $model = Template::model()->with(array('contents'=>array(
                'joinType'=>'INNER JOIN',
                'condition'=>'contents.revision_id=:revision_id',
                'params'=>array(':revision_id'=>$revisionId)
            )))->findByPk($templateId);
            if (is_object($model) && is_array($model->contents) && count($model->contents))
                $model->currentRevision = $model->contents[0];
                
        }
        else
        {
            $model = Template::model()->with('currentRevision')->findByPk($templateId);
        }
        
        if (is_object($model))
        {
            if (!is_object($model->currentRevision))
            $model->currentRevision = new TemplateContent();
        }
        else
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('Cms.Template','Invalid ID.'));
        
        $this->result->processed('model', $model);
        return $this->result;
    }
    
    /**
    * Get template content
    * 
    * @param int id Template ID
    * @param int revisionId Revision ID or 0 to get the latest
    */
    public function getContent($params) {
        $templateId = $this->getParam($params, 'id',0);
        if (!$templateId)
            return $this->result->fail(ERROR_INVALID_DATA, Yii::t('Cms.Template','Invalid ID.'));

        $revisionId = $this->getParam($params, 'revisionId',0);
        
        $criteria = new CDbCriteria();
        $criteria->compare('template_id',$templateId,false);
        $criteria->limit = 1;
        $criteria->order = 'last_update desc';
        
        $content = TemplateContent::model()->find($criteria);
        if (!$content)
            $content = new TemplateContent();
        
        $this->result->processed('templateContent',$content);
        
        return $this->result;
    }
    
    /**
    * Get template groups
    * 
    */
    public function getGroups($params) {
        $term = $this->getParam($params,'term','').'%';
//        $term = trim(end(explode(',',$term)));
        
        $sql = "SELECT DISTINCT \"group\" FROM ".SITE_TABLE_PREFIX."template
                WHERE \"group\" LIKE :term";
        
        $groups = Yii::app()->db->createCommand($sql)->queryColumn(array(':term'=>$term));
        $this->result->processed('groups', json_encode($groups));
    }

    public function save($params) {
        /**
        * @var Template
        */
        $model = $this->getModel($params['Template'],'Template');
        $isNewTemplate = $model->getIsNewRecord();
		
		/**
        * @var TemplateContent
        */
        $content = $this->getModel($params['TemplateContent'],'TemplateContent',array('html'=>'xss,tag,newline'));
        $content->status = $model->status;
        if ($model->group == 'master')
            $content->parent_id = 0;
        $model->currentRevision = $content;
        $this->result->processed('model', $model);
        
        $sameRevision = $this->getParam($params, 'same_revision', 0);
        $pageId = $this->getParam($params, 'page_id', 0);
        $pageRevision = $this->getParam($params, 'page_revision', 0);
        //use for copy widgets when new template revision
        $containers = $this->getParam($params, 'containers', array(), 'xss,tag,newline');
                    
        if (!$content->validate())
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('Cms.TemplateContent', 'Submitted data is missing or invalid.'));
        elseif ($this->getParam($params, 'validateOnly',0) == TRUE)
            return $this->result;
        else
        {
        	if (! $model->validate())
		        $this->result->fail(ERROR_INVALID_DATA, Yii::t('Cms.Template', 'Submitted data is missing or invalid.'));
		    elseif ($this->getParam($params, 'validateOnly',0) == TRUE)
		        return $this->result;
		    elseif ($model->save(false)) {
                if ($isNewTemplate)
                {
                    $revisionId = 1;
                    $newContent = $content;
                    $newContent->template_id = $model->id;
                    $newContent->status = true;
                }
                elseif ($sameRevision)
                {
                    $revisionId = $content->revision_id;
                    $newContent = $content;
                }
                else
                {
                    $lastRevision = 0;
                    $criteria = new CDbCriteria();
                    $criteria->compare('template_id', $content->template_id);
                    $criteria->order = 'revision_id DESC';
                    $templateContent = TemplateContent::model()->find($criteria);
                    if (is_object($templateContent))
                        $lastRevision = $templateContent->revision_id;
                    $revisionId = 1+(int) $lastRevision;
                    $newContent = new TemplateContent;
                    $newContent->attributes = $content->attributes;
                    $newContent->id = null;
                    $newContent->setIsNewRecord(true);
                }
                    
                $newContent->revision_id = $revisionId;
                if ($newContent->save(false))
                {
                    if ($sameRevision == false && $pageId && $pageRevision)
                    {
                        $criteria = new CDbCriteria();
                        $criteria->compare('id', $pageRevision);
                        $criteria->compare('page_id', $pageId);
                        PageRevision::model()->updateAll(array('template_content_id'=>$newContent->id), $criteria);
                    }
                    
                    //if create new template revision then copy widgets from previous revision
                    if ($sameRevision == false && $revisionId > 1 && is_array($containers) && count($containers))
                    {
                        foreach ($containers as $container => $ids)
                        {
                            if ((is_array($ids) && count($ids)) === false) continue;
                            
                            foreach ($ids as $index => $id)
                            {
                                $pageWidget = PageWidget::model()->findByPk($id);
                                if (is_object($pageWidget))
                                {
                                    $pageWidget->setIsNewRecord(true);
                                    $pageWidget->id = null;
                                    $pageWidget->template_content_id = $newContent->id;
                                    if ($pageWidget->save())
                                    {
                                        $containers[$container][$index] = $pageWidget->id;
                                    }
                                    else
                                    {
                                        Yii::log(CVarDumper::dumpAsString($pageWidget->getErrors()), CLogger::LEVEL_ERROR);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                    $this->result->fail(ERROR_HANDLING_DB, Yii::t('Cms.TemplateContent','Error while saving submitted data into database.'));    
                
                //update relationship template_site
                FSM::_run('Cms.template.updateTemplateSite', array('template_id'=>array($model->id)));
                
                $model->currentRevision = $newContent;
                $this->result->processed('model', $model);
                $this->result->processed('containers', $containers);
            } else
                $this->result->fail(ERROR_HANDLING_DB, Yii::t('Cms.TemplateContent','Error while saving submitted data into database.'));
		}
		
        return $this->result;
    }


    public function delete($params) {
        $ids = $this->getParam($params, 'ids', array());
        if ($ids == 0) {
            return $this->result->fail(ERROR_INVALID_DATA, Yii::t('Cms.Template','Invalid ID.'));
        }
      
        if (!is_array($ids)) $ids = array($ids);        
        foreach($ids as $id) {
            $model = Template::model()->findByPk($id);
            if (is_object($model))
            {
                //template is used ? no => delete it
                if (FSM::_run('Cms.pageRevision.isTemplateUsed', array('template_id'=>$id))->exists == false)
                {
                    if ($model->delete())
                    {
                        //remove relationship tempalte_site
                        $siteId = Yii::app()->cmsManager->site['id'];
                        $command = Yii::app()->db->createCommand();
                        $command->delete(SITE_TABLE_PREFIX.'template_site', 'template_id = :template_id AND site_id = :site_id', array(':template_id'=>$id, ':site_id'=>$siteId));
                        FSM::_run('Cms.templateContent.deleteByTemplateId', array('template_id'=>$id));
                    }
                }
                else
                {
                    $this->result->fail(ERROR_INVALID_DATA, "Can't delete this template. Template be using by some pages.");
                }
            }
            else
            {
                $this->result->fail(ERROR_HANDLING_DB, $ex->getMessage());
            }
        }
        return $this->result;
    }
    
    public function getList()
    {
        $criteria = new CDbCriteria();
        $criteria->compare('status', true);
        $criteria->order = 'name';
        $models = Template::model()->findAll($criteria);
        $this->result->processed('models', $models);
        return $this->result;
    }
    
    public function changeStatus($params) {
        $ids = $this->getParam($params, 'ids', array());
        $value = $this->getParam($params, 'value', false);
        
        if (count($ids) <= 0)
            return $this->result;
        
        $criteria = new CDbCriteria();
        $criteria->addInCondition('id', $ids);
        Template::model()->updateAll(array('status'=>$value), $criteria);
        
        return $this->result;
    }
    
    public function updateTemplateSite($params)
    {
        $templateIds = $this->getParam($params, 'template_id', array());
        $siteId = $this->getParam($params, 'site_id', Yii::app()->cmsManager->site['id']);
        
        $status = false;
        $command = Yii::app()->db->createCommand();
        if (count($templateIds))
        {
            foreach ($templateIds as $templateId)
            {
                $command->reset();
                $exist = $command->select('COUNT(*)')
                    ->from(SITE_TABLE_PREFIX.'template_site')
                    ->where('template_id = :template_id AND site_id = :site_id', array(':template_id'=>$templateId, ':site_id'=>$siteId))
                    ->queryScalar();
                if (! $exist)
                {
                    $command->reset();
                    $status = $command->insert(SITE_TABLE_PREFIX.'template_site', array(
                        'template_id'=>$templateId,
                        'site_id'=>$siteId,
                    ));
                }
            }
        }
        return $this->result->processed('status', $status);
    }
}